package models.admin;

import jodd.bean.BeanCopy;
import models.BaseModel;
import models.admin.enums.AdminUserAuth;
import models.admin.enums.AdminUserType;
import models.constants.AvailableStatus;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.crop.Corp;
import models.weixin.crop.Tag;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.Map;
import java.util.Set;

/**
 * Created by liming on 16/6/29.
 */
@Entity
@Table(name = "admin_user")
public class AdminUser extends BaseModel {
    public static String LOGIN_TAG = "admin_tag";

    /**
     * 所属企业号公司.
     */
    @ManyToOne
    @JoinColumn(name = "corp_id")
    public Corp corp;

    /**
     * 员工UserId.
     *
     * 对应管理端的帐号，企业内必须唯一。长度为1~64个字符.
     */
    @Column(name = "wx_user_id", length = 64)
    public String wxUserId;

    /**
     * 邮箱
     */
    @Column(name = "email")
    public String email;

    /**
     * 电话
     */
    @Column(name = "mobile")
    public String mobile;

    /**
     * 图片
     */
    @Column(name = "pic_url")
    public String picUrl;

    /**
     * 定位
     */
    @Column(name = "position")
    public String position;

    // ------------------------ 一期只用这几个 start ------------------------------

    /**
     * 名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 登陆名
     */
    @Column(name = "login_name")
    public String loginName;

    /**
     * 密码
     */
    @Column(name = "password")
    public String password;

    /**
     * 联系电话
     */
    @Column(name = "phone_no")
    public String phoneNo;

    /**
     * 所属店面
     */
    @JoinColumn(name="merchant_id")
    @ManyToOne
    public Merchant merchant;

    // ------------------------ 一期只用这几个 end ------------------------------

    /**
     * 隶属部门
     */

    @ManyToOne
    @JoinColumn(name = "admin_dept_id")
    public AdminDept adminDept;

    /**
     * 适用状态
     */
    @Column(name = "available_status")
    @Enumerated(EnumType.STRING)
    public AvailableStatus availableStatus;

    /**
     * 用户类型
     */
    @Column(name = "admin_user_type")
    @Enumerated(EnumType.STRING)
    public AdminUserType adminUserType;

    /**
     * 用户权限类型
     */
    @Column(name = "admin_user_auth")
    @Enumerated(EnumType.STRING)
    public AdminUserAuth adminUserAuth;

    /**
     * 外协公司名称
     */
    @Column(name = "outsourcing_company")
    public String outsourcingCompany;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    @Column(name = "deleted")
    public DeletedStatus deleted = DeletedStatus.UN_DELETED;

    /**
     * 创建人Id
     */
    @Column(name = "ct_user_id")
    public Long ctUserId;

    @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinTable(name = "wxcp_depts_users",
            inverseJoinColumns = @JoinColumn(name = "dept_id"),
            joinColumns = @JoinColumn(name = "user_id"))
    public Set<AdminDept> depts;


    @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinTable(name = "wxcp_tags_users",
            inverseJoinColumns = @JoinColumn(name = "tag_id"),
            joinColumns = @JoinColumn(name = "user_id"))
    public Set<Tag> tags;

    /**
     * 分页查询.
     */
    public static JPAExtPaginator<AdminUser> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder("t.deleted=models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.name like {name} ~/")
                .append("/~ and t.loginName like {loginName} ~/")
                .append("/~ and t.phoneNo like {phoneNo} ~/")
                .append("/~ and t.merchant = {merchant} ~/");

        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<AdminUser> orderPage = new JPAExtPaginator<AdminUser>("AdminUser t", "t", AdminUser.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }

//    /**
//     * Update
//     * @param id
//     * @param newObject
//     */
//    public static void update(Long id, AdminUser newObject) {
//        AdminUser adminUser = AdminUser.findById(id);
//        BeanCopy.beans(newObject, adminUser).ignoreNulls(true).copy();
//        adminUser.save();
//    }


    /**
     * 通过id查询用户
     */
    public static AdminUser findAdminUserById(long id) {
        return AdminUser.find("id=?1 and deleted=?2", id, DeletedStatus.UN_DELETED).first();
    }


    /**
     * 找出corp中的指定wxUserId的用户.
     */
    public static AdminUser findCorpWxUser(Corp corp, String wxUserId) {
        return AdminUser.find("corp.id=?1 and wxUserId=?2", corp.id, wxUserId).first();
    }


    /**
     * 找出wxUserId的用户.
     */
    public static AdminUser findByWeixinUserId(String wxUserId) {
        return AdminUser.find("wxUserId=?1", wxUserId).first();
    }

    public static AdminUser findByLoginName(String loginName) {
        return AdminUser.find("loginName = ?1 and deleted = ?2" , loginName , DeletedStatus.UN_DELETED).first();
    }
    public static void  update(AdminUser adminUser){
        AdminUser oldEntity =  AdminUser.findById(adminUser.id);
        BeanCopy.beans(adminUser,oldEntity).ignoreNulls(true).copy();
        adminUser.save();
    }

}
